package com.mayjean.db.tenant;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.Objects;

/**
 * nezha tenant handler
 *
 * @author kyleju
 */
@RequiredArgsConstructor
public class NezhaTenantHandler implements TenantHandler {

	private final NezhaTenantProperties tenantProperties;
	private final ITenantId iTenantId;

	@Override
	public Expression getTenantId(boolean where) {
		if (iTenantId != null) {
			String tenantId = iTenantId.getTenantId(where);
			if (Objects.isNull(tenantId)) {
				return null;
			}
			return new StringValue(tenantId);
		}
		return null;
	}

	@Override
	public String getTenantIdColumn() {
		return tenantProperties.getField();
	}

	@Override
	public boolean doTableFilter(String tableName) {
		if (Objects.isNull(tenantProperties.getField())) {
			return false;
		}

		if (tenantProperties.getTables() != null) {
			return tenantProperties.getTables().contains(tableName);
		} else if (tenantProperties.getExclusionTables() != null) {
			return !tenantProperties.getExclusionTables().contains(tableName);
		} else {
			return false;
		}
	}
}
